<template>
  <div class="customer-management">
    <div class="page-header">
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增客户</el-button>
        <div class="search-box">
          <el-input v-model="searchText" placeholder="请输入客户姓名/手机号搜索" style="width: 300px;" clearable
            @clear="handleSearch" @keyup.enter.native="handleSearch">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </div>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" stripe border v-loading="loading">
        <el-table-column prop="clientName" label="姓名"></el-table-column>
        <el-table-column prop="clientSex" label="性别">
          <template slot-scope="scope">
            {{ scope.row.clientSex === 0 ? '女' : '男' }}
          </template>
        </el-table-column>
        <el-table-column prop="clientPhone" label="电话"></el-table-column>
        <el-table-column prop="clientLentenName" label="租赁意向"></el-table-column>
        <el-table-column prop="enterPerson" label="录入人"></el-table-column>
        <el-table-column prop="enterTime" label="录入时间"></el-table-column>
        <el-table-column prop="clientDesc" label="备注"></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #f56c6c;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.current" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @closed="handleDialogClosed">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="客户姓名" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="clientSex">
          <el-radio-group v-model="form.clientSex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="clientPhone">
          <el-input v-model="form.clientPhone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="租赁意向" prop="lntentId">
          <el-select v-model="form.lntentId" placeholder="请选择租赁意向" style="width: 100%">
            <el-option label="车位" :value="1"></el-option>
            <el-option label="广告位" :value="2"></el-option>
            <el-option label="房屋" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="录入人" prop="enterPerson">
          <el-input v-model="form.enterPerson" placeholder="请输入录入人"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="clientDesc">
          <el-input type="textarea" v-model="form.clientDesc" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CustomerManagement',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'))
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        return callback(new Error('请输入正确的手机号码'))
      }
      callback()
    }

    return {
      searchText: '',
      loading: false,
      dialogVisible: false,
      dialogTitle: '新增客户',
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      form: {
        clientId: '',
        clientName: '',
        clientSex: 1,
        clientPhone: '',
        lntentId: 1,
        enterPerson: '',
        clientDesc: ''
      },
      rules: {
        clientName: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        clientSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        clientPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        lntentId: [
          { required: true, message: '请选择租赁意向', trigger: 'change' }
        ],
        enterPerson: [
          { required: true, message: '请输入录入人', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取客户列表
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.current,
          size: this.pagination.size,
          keyword: this.searchText
        }
        const res = await request.post('/client/getClientList', params)

        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
          this.pagination.current = res.data.current
          this.pagination.size = res.data.size
        } else {
          this.$message.error(res.message || '获取客户列表失败')
        }
      } catch (error) {
        console.error('获取客户列表失败:', error)
        this.$message.error('获取客户列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.fetchData()
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchData()
    },

    // 新增客户
    handleAdd() {
      this.dialogTitle = '新增客户'
      this.dialogVisible = true
      this.form = {
      }
    },

    // 编辑客户
    handleEdit(row) {
      this.dialogTitle = '编辑客户'
      this.dialogVisible = true
      this.form = {
        clientId: row.clientId,
        clientName: row.clientName,
        clientSex: row.clientSex === '男' ? 1 : 0,
        clientPhone: row.clientPhone,
        lntentId: this.getIntentId(row.clientLentenName),
        enterPerson: row.enterPerson,
        clientDesc: row.clientDesc || ''
      }
    },

    // 获取租赁意向ID
    getIntentId(name) {
      switch (name) {
        case '车位': return 1
        case '广告位': return 2
        case '房屋': return 3
        default: return 1
      }
    },

    // 删除客户
    handleDelete(row) {
      this.$confirm(`确定要删除客户 "${row.clientName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request.delete(`/client/deleteClient?clientId=${row.clientId}`)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除客户失败:', error)
          this.$message.error('删除客户失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            const res = await request.post('/client/updateClient', this.form)
            if (res.code === 200) {
              this.$message.success(this.form.clientId ? '修改成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || '操作失败')
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败')
          }
        } else {
          return false
        }
      })
    },

    // 对话框关闭
    handleDialogClosed() {
      this.$refs.form.resetFields()
      this.form.clientId = ''
    }
  }
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
}

.table-container {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  padding: 20px;
  text-align: right;
}
</style>
